package com.mby.controller;

import com.mby.entity.CommonWords;
import com.mby.entity.Dealer;
import com.mby.entity.WelcomeWords;
import com.mby.entity.WordsGroup;
import org.springframework.data.mongodb.core.aggregation.ArrayOperators;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * Created by noah on 2018/4/18.
 */
@RestController
public class CommonWordsController extends BaseController{

    /**
     * 创建一个常用语
     * post /live/common_words
     * @param commonWords(content,group_id)
     */
    @PostMapping(value = "/common_words", produces = "application/json; charset=UTF-8")
    public void create_common_words(@RequestBody CommonWords commonWords){
        long count = mongoTool.count("{'id':"+commonWords.getGroupId()+"}",WordsGroup.class);
        if(count > 0){
            commonWords.setDealerId(currentUser().getDealerId());
            respData(mongoTool.addOne(commonWords));
        }else{
            respErr("Nonexistent Group");
        }
    }

    /**
     * 修改一个常用语
     * put /live/common_words/{id}
     * @param id
     * @param commonWords(content,group_id)
     */
    @PutMapping(value = "/common_words/{id}", produces = "application/json; charset=UTF-8")
    public void update_common_words(@PathVariable Integer id,@RequestBody CommonWords commonWords){
        mongoTool.update(commonWords,"{'id':"+id+",'dealerId':'"+currentUser().getDealerId()+"'}",CommonWords.class);
        respData(ok);
    }

    /**
     * 删除一个常用语
     * delete /live/common_words/{:id}
     * @param id
     */
    @DeleteMapping(value = "/common_words/{id}")
    public void delete_common_words(@PathVariable Integer id){
        mongoTool.update("{'deletedAt':'"+getNow()+"','deleted':true}","{'id':"+id+",'dealerId':'"+currentUser().getDealerId()+"'}",CommonWords.class);
        respData(ok);
    }

    /**
     * 查找当前用户的所有有效(未删除的)常用语
     * get /live/common_words?group_id=1&page_no=1&page_size=10
     */
    @GetMapping(value = "/common_words")
    public void get_common_words(Integer group_id,Integer page_no,Integer page_size){
        CommonWords cw = new CommonWords();
        cw.setGroupId(group_id);
        cw.setDealerId(currentUser().getDealerId());
        cw.setDeleted(false);
        List<?> list = mongoTool.findMany(cw,"id",CommonWords.class);
        List<CommonWords> result = new ArrayList<>();
        if(list != null && page_no != null && page_size != null){
            page_no = page_no -1;
            int i = page_no*page_size;
            while(i>=page_no*page_size && i<(page_no+1)*page_size && i<list.size()){
                cw = (CommonWords) list.get(i);
                result.add(cw);
                i++;
            }
            resultMap.put("total",list.size());
            resultMap.put("list",result);
            respData(resultMap);
        }else{
            respData(list);
        }
    }

    /**
     * 创建一个常用语分类
     * post /live/words_groups
     * @param wordsGroup(name)
     */
    @PostMapping(value = "/words_groups", produces = "application/json; charset=UTF-8")
    public void create_words_group(@RequestBody WordsGroup wordsGroup){
        wordsGroup.setDealerId(currentUser().getDealerId());
        respData(mongoTool.addOne(wordsGroup));
    }

    /**
     * 修改一个常用语分类
     * put /live/words_groups/{id}
     * @param id
     * @param wordsGroup(name)
     */
    @PutMapping(value = "/words_groups/{id}", produces = "application/json; charset=UTF-8")
    public void update_words_group(@PathVariable Integer id,@RequestBody WordsGroup wordsGroup){
        mongoTool.update(wordsGroup,"{'id':"+id+",'dealerId':'"+currentUser().getDealerId()+"'}",WordsGroup.class);
        respData(ok);
    }

    /**
     * 删除一个常用语分类
     * delete /live/words_groups/{:id}
     * @param id
     */
    @DeleteMapping(value = "/words_groups/{id}")
    public void delete_words_group(@PathVariable Integer id){
        mongoTool.update("{'deletedAt':'"+getNow()+"','deleted':true}","{'id':"+id+",'dealerId':'"+currentUser().getDealerId()+"'}",WordsGroup.class);
        respData(ok);
    }

    /**
     * 查找当前用户的所有有效(未删除的)常用语分组
     * get /live/words_groups
     */
    @GetMapping(value = "/words_groups")
    public void get_words_groups(){
        respData(mongoTool.findMany("{'dealerId':'"+currentUser().getDealerId()+"','deleted':false}","name",WordsGroup.class));
    }

    static Set<String> common = new LinkedHashSet<>();

    /**
     * 初始化常用语分组和常用语
     * get /live/init/welcome_words
     * @throws Exception
     */
    @GetMapping(value = "/init/common_words")
    public void initWelcomeWords() throws Exception{
        String[] groups = {"服务顾问","技师","部件养护"};

        common.add("服务顾问#尊贵的客户，您好！欢迎加入“保养服务直播间”，本群中由我和技师以及售后经理、车间主管、前台主管共同为您服务。本次保养流程如下：全车31项健康检查》保养及维修》质检》免费基础洗车》结算交车。");
        common.add("服务顾问#尊贵的车主，您好！本次“保养服务直播间”体验已结束！稍后我的名片会推送给您，您可以在车主APP经销商查询页面查看。欢迎随时联系我，祝您用车愉快！ ");
        common.add("技师#尊贵的客户，您好！我是本次的保养技师，您将了解到整个的施工过程。");
        common.add("技师#现在开始车辆检查，详情检查报告稍后系统发送给您。");
        common.add("技师#保养零件准备就绪，开始施工。");
        common.add("技师#现在使用捷豹路虎专用设备进行全车电脑检测。");
        common.add("技师#本次保养已结束，等待质检和洗车。祝您用车愉快！");
        common.add("技师#车辆已完成清洗，质检合格，期待您到交车区与我们共同检验保养成果！");
        common.add("部件养护#根据捷豹路虎厂家售后标准，前刹车片厚度小于5毫米是警戒线，按标准更换刹车片可以最大限度保障您的驾驶安全！");
        common.add("部件养护#根据捷豹路虎厂家售后标准，后刹车片厚度小于5毫米是警戒线，按标准更换刹车片可以最大限度保障您的驾驶安全！");
        common.add("部件养护#根据捷豹路虎厂家售后标准，前刹车盘凹槽厚度小于3毫米是警戒线，按标准更换刹车盘可以最大限度保障您的驾驶安全！");
        common.add("部件养护#根据捷豹路虎厂家售后标准，后刹车盘凹槽厚度小于3毫米是警戒线，按标准更换刹车盘可以最大限度保障您的驾驶安全！");
        common.add("部件养护#磨损：根据捷豹路虎厂家售后标准，前轮胎胎纹深度小于5毫米是警戒线，按标准更换轮胎可以最大限度保障您的驾驶安全！");
        common.add("部件养护#磨损：根据捷豹路虎厂家售后标准，后轮胎胎纹深度小于5毫米是警戒线，按标准更换轮胎可以最大限度保障您的驾驶安全！");
        common.add("部件养护#根据捷豹路虎厂家售后标准，建议每2.5年更换一次原厂蓄电瓶，按标准更换蓄电瓶可以最大限度保障您爱车的电器系统及电脑可靠性！");
        common.add("部件养护#根据捷豹路虎厂家售后标准，建议每半年更换一次原厂雨刮片，按标准更换雨刮片可以保证您在恶劣天气下的驾驶安全性！");
        common.add("部件养护#根据捷豹路虎厂家售后标准，建议每3年更换一次原厂刹车油，按标准更换刹车油可以保证您的驾驶安全！");
        common.add("部件养护#根据捷豹路虎厂家售后标准，建议每1万公里或者每年更换一次原厂PM2.5空调滤芯，同时建议每半年进行一次空调清洗，按标准更换空调滤芯或者清洗可以保证您的身心健康！");
        common.add("部件养护#根据捷豹路虎厂家售后标准，建议每1万公里或者每X年更换一次原厂燃油添加剂，按标准使用燃油添加剂可以提升您的爱车动力！");

        List<?> list = mongoTool.findMany("","","",Dealer.class);
        if(list.size() > 0){
            Dealer dealer; WordsGroup wordsGroup; CommonWords commonWords; String groupName;
            for(int i=0;i<list.size();i++){
                dealer = (Dealer)list.get(i);

                mongoTool.delete("{'dealerId':'"+dealer.getId()+"'}",CommonWords.class);
                mongoTool.delete("{'dealerId':'"+dealer.getId()+"'}",WordsGroup.class);

                for(int j=0;j<groups.length;j++){
                    wordsGroup = new WordsGroup();
                    wordsGroup.setDealerId(dealer.getId());
                    wordsGroup.setName(groups[j]);
                    mongoTool.addOne(wordsGroup);
                }

                for(String content:common){
                    groupName = content.split("#")[0];
                    content = content.split("#")[1];
                    wordsGroup = mongoTool.findOne("","{'dealerId':'"+dealer.getId()+"','name':'"+groupName+"'}",WordsGroup.class);
                    if(wordsGroup != null){
                        commonWords = new CommonWords();
                        commonWords.setDealerId(dealer.getId());
                        commonWords.setContent(content);
                        commonWords.setGroupId(wordsGroup.getId());
                        mongoTool.addOne(commonWords);
                    }
                }
                System.out.println(list.size() + "/" + i + ":" + dealer.getId() + "finished");
            }
        }
        respData(list.size());
    }
}
